// 特征工厂页面
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Layout, Card, Form, Input, Select, Button, Table, message, Space, Typography, Tag, Divider, Modal, Tabs, Progress } from 'antd';
import { PlusOutlined, DeleteOutlined, SaveOutlined, PlayCircleOutlined, ToolOutlined, EyeOutlined, FileTextOutlined, PauseOutlined, DownloadOutlined, LineChartOutlined } from '@ant-design/icons';
import { mockService } from '../services/mockService';
import type { FeatureTask, FlowData, Dataset, Column } from '../types';
import FeatureFlowCanvas from '../components/FeatureFlowCanvas';
import { formatDateTime, formatFileSize } from '../utils/fileUtils';
import * as yaml from 'js-yaml';

const { Content } = Layout;
const { Text, Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

const FeaturesPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('1');
  
  // 特征工程页签相关状态
  const [featureTasks, setFeatureTasks] = useState<FeatureTask[]>([]);
  const [currentTask, setCurrentTask] = useState<FeatureTask | null>(null);
  const [taskLoading, setTaskLoading] = useState(false);
  const [createTaskModalVisible, setCreateTaskModalVisible] = useState(false);
  const [taskForm] = Form.useForm();
  const [datasets, setDatasets] = useState<Dataset[]>([]);
  const [flowData, setFlowData] = useState<FlowData | undefined>(undefined);
  const [yamlContent, setYamlContent] = useState<string>('');
  const [logs, setLogs] = useState<string[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  
  // 特征视图相关状态（暂时未使用，保留用于未来功能）
  // const [featureViews, setFeatureViews] = useState<FeatureView[]>([]);
  // const [loading, setLoading] = useState(false);
  // const [form] = Form.useForm();
  // const [modalVisible, setModalVisible] = useState(false);
  // const [editingFeatureView, setEditingFeatureView] = useState<FeatureView | null>(null);
  
  // 特征浏览相关状态
  const [previewDataset, setPreviewDataset] = useState<Dataset | null>(null);
  const [previewData, setPreviewData] = useState<any[]>([]);
  const [previewColumns, setPreviewColumns] = useState<any[]>([]);
  const [previewPagination, setPreviewPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 特征分析相关状态
  interface FeatureAnalysisTask {
    datasetId: string;
    status: 'pending' | 'running' | 'completed' | 'failed';
    progress: number;
    result?: FeatureAnalysisResult;
  }

  interface FeatureAnalysisResult {
    featureCount: number;
    featureTypes: { [key: string]: number };
    missingValues: { [key: string]: number };
    dataQuality: {
      completeness: number;
      uniqueness: number;
      consistency: number;
      overallQuality: number;
    };
    featureStatistics: { [key: string]: { min?: number; max?: number; mean?: number; std?: number } };
  }

  // 预定义的特征分析结果示例
  const mockAnalysisResults: { [key: string]: FeatureAnalysisResult } = {
    '2': {
      featureCount: 12,
      featureTypes: {
        'string': 4,
        'number': 6,
        'boolean': 2
      },
      missingValues: {
        'user_id': 0,
        'age': 2,
        'gender': 1,
        'purchase_amount': 0,
        'category': 3
      },
      dataQuality: {
        completeness: 96.2,
        uniqueness: 98.7,
        consistency: 94.5,
        overallQuality: 95.8
      },
      featureStatistics: {
        'age': {
          min: 18,
          max: 65,
          mean: 32.4,
          std: 12.3
        },
        'purchase_amount': {
          min: 15.5,
          max: 2450.0,
          mean: 128.7,
          std: 87.6
        },
        'login_frequency': {
          min: 0,
          max: 50,
          mean: 12.3,
          std: 8.7
        }
      }
    },
    '3': {
      featureCount: 18,
      featureTypes: {
        'string': 5,
        'number': 10,
        'boolean': 3
      },
      missingValues: {
        'transaction_id': 0,
        'amount': 0,
        'account_balance': 1,
        'credit_score': 2
      },
      dataQuality: {
        completeness: 98.5,
        uniqueness: 99.2,
        consistency: 97.1,
        overallQuality: 97.8
      },
      featureStatistics: {
        'amount': {
          min: 10.0,
          max: 50000.0,
          mean: 2350.5,
          std: 4500.2
        },
        'account_balance': {
          min: -500.0,
          max: 1000000.0,
          mean: 12500.8,
          std: 28750.3
        },
        'credit_score': {
          min: 300,
          max: 850,
          mean: 675.3,
          std: 112.4
        },
        'transaction_count': {
          min: 0,
          max: 150,
          mean: 24.7,
          std: 18.9
        }
      }
    }
  };

  const [analysisTasks, setAnalysisTasks] = useState<FeatureAnalysisTask[]>([]);
  const [currentAnalysisResult, setCurrentAnalysisResult] = useState<FeatureAnalysisResult | null>(null);
  const [analyzedDataset, setAnalyzedDataset] = useState<Dataset | null>(null);


  useEffect(() => {
    if (activeTab === '1') {
      loadFeatureTasks();
      loadDatasets();
    } else if (activeTab === '2' || activeTab === '3') {
      // 特征浏览和特征分析都需要加载特征集
      loadDatasets();
    }
  }, [activeTab]);

  
  // 将FlowData转换为YAML - 使用 useMemo 优化
  const yamlContentMemo = useMemo(() => {
    try {
      if (!flowData || !flowData.nodes || !flowData.connections) {
        return '# 暂无工作流配置';
      }
      const yamlObj = {
        workflow: {
          nodes: flowData.nodes.map(node => ({
            id: node.id,
            type: node.type,
            name: node.name,
            properties: node.properties || {}
          })),
          connections: flowData.connections.map(conn => ({
            from: conn.source,
            to: conn.target,
            sourceHandle: conn.sourceHandle,
            targetHandle: conn.targetHandle
          }))
        }
      };
      return yaml.dump(yamlObj, { indent: 2 });
    } catch (error) {
      console.error('生成YAML失败:', error);
      return '# YAML生成错误';
    }
  }, [flowData]);

  useEffect(() => {
    if (currentTask?.flowData) {
      setFlowData(currentTask.flowData);
      setLogs(currentTask.logs || []);
    } else {
      setFlowData(undefined);
      setYamlContent('# 暂无工作流配置');
      setLogs([]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentTask]);
  
  // 使用 useMemo 的结果来更新 YAML 内容
  useEffect(() => {
    setYamlContent(yamlContentMemo);
  }, [yamlContentMemo]);

  // 加载特征任务列表
  const loadFeatureTasks = async () => {
    try {
      setTaskLoading(true);
      const response = await mockService.featureTasks.getAll();
      if (response.success && response.data) {
        setFeatureTasks(response.data);
      }
    } catch (error) {
      console.error('加载特征任务失败:', error);
      message.error('加载特征任务失败');
    } finally {
      setTaskLoading(false);
    }
  };
  
  // 加载特征集列表（只显示经过特征工程处理的数据集）
  const loadDatasets = async () => {
    try {
      const response = await mockService.datasets.getAll();
      if (response.success && response.data) {
        // 只显示标记为特征集的数据集，或者根据特定条件过滤
      const featureDatasets = response.data.filter(dataset => 
        dataset.type === 'feature' || dataset.name.includes('特征') || dataset.description?.includes('特征') || dataset.description?.includes('特征工程')
      );
        console.log('加载的数据集:', response.data);
        console.log('过滤后的特征集:', featureDatasets);
        setDatasets(featureDatasets);
      }
    } catch (error) {
      console.error('加载特征集失败:', error);
    }
  };
  
  
  // 创建新任务
  const handleCreateTask = () => {
    setCreateTaskModalVisible(true);
    taskForm.resetFields();
  };
  
  // 提交创建任务
  const handleTaskSubmit = async (values: any) => {
    try {
      setTaskLoading(true);
      // 使用默认数据集ID，避免需要用户选择
      const defaultDatasetId = '1'; // 使用mockService.ts中定义的第一个数据集
      const response = await mockService.featureTasks.create({
        name: values.name,
        type: 'visual',
        datasetId: defaultDatasetId,
        flowData: {
          nodes: [],
          connections: []
        }
      });
      
      if (response.success && response.data) {
        message.success('任务创建成功');
        setCreateTaskModalVisible(false);
        taskForm.resetFields();
        await loadFeatureTasks();
        // 打开新创建的任务
        setCurrentTask(response.data);
        setFlowData(response.data.flowData);
      } else {
        message.error(response.error || '创建任务失败');
      }
    } catch (error) {
      message.error('创建任务失败');
    } finally {
      setTaskLoading(false);
    }
  };
  
  // 打开任务编辑
  const handleOpenTask = async (task: FeatureTask) => {
    const response = await mockService.featureTasks.getById(task.id);
    if (response.success && response.data) {
      setCurrentTask(response.data);
      setFlowData(response.data.flowData);
      setLogs(response.data.logs || []);
    }
  };
  
  // 从列表运行任务
  const handleRunTaskFromList = async (task: FeatureTask) => {
    if (task.status === 'running') {
      message.warning('任务正在运行中');
      return;
    }
    
    try {
      const response = await mockService.featureTasks.run(task.id);
      if (response.success) {
        message.success('任务已开始运行');
        await loadFeatureTasks();
        
        // 如果当前正在编辑这个任务，更新状态
        if (currentTask?.id === task.id) {
          const updatedResponse = await mockService.featureTasks.getById(task.id);
          if (updatedResponse.success && updatedResponse.data) {
            setCurrentTask(updatedResponse.data);
            setLogs(updatedResponse.data.logs || []);
          }
        }
      } else {
        message.error(response.error || '运行任务失败');
      }
    } catch (error) {
      message.error('运行任务失败');
    }
  };
  
  // 暂停任务
  const handlePauseTask = async (task: FeatureTask) => {
    if (task.status !== 'running') {
      message.warning('任务未在运行中');
      return;
    }
    
    try {
      const response = await mockService.featureTasks.pause(task.id);
      if (response.success) {
        message.success('任务已暂停');
        await loadFeatureTasks();
        
        // 如果当前正在编辑这个任务，更新状态
        if (currentTask?.id === task.id) {
          const updatedResponse = await mockService.featureTasks.getById(task.id);
          if (updatedResponse.success && updatedResponse.data) {
            setCurrentTask(updatedResponse.data);
            setLogs(updatedResponse.data.logs || []);
          }
        }
      } else {
        message.error(response.error || '暂停任务失败');
      }
    } catch (error) {
      message.error('暂停任务失败');
    }
  };
  
  // 删除任务
  const handleDeleteTask = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个任务吗？',
      onOk: async () => {
        try {
          const response = await mockService.featureTasks.delete(id);
          if (response.success) {
            message.success('删除成功');
            if (currentTask?.id === id) {
              setCurrentTask(null);
              setFlowData(undefined);
              setYamlContent('');
              setLogs([]);
            }
            await loadFeatureTasks();
          } else {
            message.error(response.error || '删除失败');
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };
  
  // 保存流程数据 - 使用防抖优化
  const saveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
  
  const handleFlowChange = useCallback(async (data: FlowData) => {
    setFlowData(data);
    
    // 清除之前的保存定时器
    if (saveTimerRef.current) {
      clearTimeout(saveTimerRef.current);
    }
    
    // 延迟保存，避免频繁保存
    if (currentTask) {
      saveTimerRef.current = setTimeout(async () => {
        try {
          await mockService.featureTasks.update(currentTask.id, { flowData: data });
        } catch (error) {
          console.error('保存流程数据失败:', error);
        }
      }, 1000); // 1秒后保存
    }
  }, [currentTask]);
  
  // 运行任务
  const handleRunTask = async () => {
    if (!currentTask) {
      message.warning('请先选择一个任务');
      return;
    }
    
    if (!flowData || flowData.nodes.length === 0) {
      message.warning('请先添加组件到画布');
      return;
    }
    
    setIsRunning(true);
    setLogs(['开始运行特征工程任务...']);
    
    try {
      // 先保存流程数据
      if (currentTask) {
        await mockService.featureTasks.update(currentTask.id, { flowData });
      }
      
      // 运行任务
      const response = await mockService.featureTasks.run(currentTask.id);
      if (response.success) {
        // 模拟日志输出
        const logMessages = [
          '初始化工作流...',
          '加载特征集...',
          '执行数据预处理...',
          '执行特征操作...',
          '合并数据...',
          '生成输出...',
          '任务执行完成！'
        ];
        
        logMessages.forEach((msg, index) => {
          setTimeout(() => {
            setLogs(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${msg}`]);
          }, (index + 1) * 1000);
        });
        
        // 更新任务状态
        setTimeout(async () => {
          await loadFeatureTasks();
          const updatedResponse = await mockService.featureTasks.getById(currentTask.id);
          if (updatedResponse.success && updatedResponse.data) {
            setCurrentTask(updatedResponse.data);
            setLogs(updatedResponse.data.logs || []);
          }
          setIsRunning(false);
        }, logMessages.length * 1000);
      } else {
        message.error(response.error || '运行任务失败');
        setIsRunning(false);
      }
    } catch (error) {
      message.error('运行任务失败');
      setIsRunning(false);
    }
  };

  // 特征视图相关函数（暂时未使用，保留用于未来功能）
  // const loadFeatureViews = async () => { ... };
  // const handleCreate = () => { ... };
  // const handleEdit = (featureView: FeatureView) => { ... };
  // const handleDelete = async (id: string) => { ... };
  // const handleSubmit = async (values: any) => { ... };

  // 预定义的预览数据示例
  const mockPreviewData: { [key: string]: any[] } = {
    '2': [
      {
        user_id: 'user_001',
        age: 28,
        gender: 'male',
        purchase_amount: 125.50,
        category: 'electronics',
        login_frequency: 12,
        last_login: '2023-05-15',
        is_vip: true,
        registration_date: '2022-01-10 14:30:22',
        avg_session_duration: 15.3
      },
      {
        user_id: 'user_002',
        age: 34,
        gender: 'female',
        purchase_amount: 89.99,
        category: 'clothing',
        login_frequency: 8,
        last_login: '2023-05-18',
        is_vip: false,
        registration_date: '2022-03-22 09:15:45',
        avg_session_duration: 12.7
      },
      {
        user_id: 'user_003',
        age: 45,
        gender: 'male',
        purchase_amount: 356.75,
        category: 'home',
        login_frequency: 15,
        last_login: '2023-05-20',
        is_vip: true,
        registration_date: '2021-11-05 16:45:18',
        avg_session_duration: 18.2
      },
      {
        user_id: 'user_004',
        age: 22,
        gender: 'female',
        purchase_amount: 45.20,
        category: 'beauty',
        login_frequency: 5,
        last_login: '2023-05-10',
        is_vip: false,
        registration_date: '2023-01-15 11:20:33',
        avg_session_duration: 8.5
      },
      {
        user_id: 'user_005',
        age: 38,
        gender: 'male',
        purchase_amount: 210.00,
        category: 'sports',
        login_frequency: 18,
        last_login: '2023-05-22',
        is_vip: true,
        registration_date: '2020-08-30 13:55:07',
        avg_session_duration: 22.1
      }
    ],
    '3': [
      {
        transaction_id: 'txn_1001',
        amount: 5000.00,
        account_balance: 25000.50,
        credit_score: 720,
        transaction_count: 12,
        account_age_months: 36,
        risk_level: 'low',
        last_transaction: '2023-05-18',
        is_fraud: false,
        transaction_datetime: '2023-05-18 14:22:35'
      },
      {
        transaction_id: 'txn_1002',
        amount: 1500.75,
        account_balance: 8750.25,
        credit_score: 680,
        transaction_count: 8,
        account_age_months: 24,
        risk_level: 'medium',
        last_transaction: '2023-05-19',
        is_fraud: false,
        transaction_datetime: '2023-05-19 09:45:12'
      },
      {
        transaction_id: 'txn_1003',
        amount: 25000.00,
        account_balance: 150000.00,
        credit_score: 780,
        transaction_count: 25,
        account_age_months: 60,
        risk_level: 'low',
        last_transaction: '2023-05-20',
        is_fraud: false,
        transaction_datetime: '2023-05-20 16:30:45'
      },
      {
        transaction_id: 'txn_1004',
        amount: 750.30,
        account_balance: -200.50,
        credit_score: 620,
        transaction_count: 5,
        account_age_months: 12,
        risk_level: 'high',
        last_transaction: '2023-05-15',
        is_fraud: true,
        transaction_datetime: '2023-05-15 11:15:28'
      },
      {
        transaction_id: 'txn_1005',
        amount: 12000.00,
        account_balance: 75000.80,
        credit_score: 750,
        transaction_count: 18,
        account_age_months: 48,
        risk_level: 'low',
        last_transaction: '2023-05-21',
        is_fraud: false,
        transaction_datetime: '2023-05-21 13:40:55'
      }
    ]
  };

  // 生成预览数据
  const generatePreviewData = (dataset: Dataset, page: number, pageSize: number) => {
    // 检查是否有预定义的示例数据
    const predefinedData = mockPreviewData[dataset.id];
    if (predefinedData) {
      const totalData = predefinedData.length;
      const startIndex = (page - 1) * pageSize;
      const endIndex = Math.min(startIndex + pageSize, totalData);
      
      // 返回预定义数据的分页结果
      const data = predefinedData.slice(startIndex, endIndex);
      return { data, total: totalData };
    }
    
    // 否则使用原有的随机生成逻辑
    const fields = dataset.columns || [];
    const totalData = dataset.rows || 100;
    const startIndex = (page - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, totalData);
    
    const data = [];
    for (let i = startIndex; i < endIndex; i++) {
      const row: any = {};
      fields.forEach((field: Column) => {
        switch (field.type) {
          case 'string':
            row[field.name] = `${field.name}_${i + 1}`;
            break;
          case 'number':
            row[field.name] = Math.floor(Math.random() * 1000);
            break;
          case 'boolean':
            row[field.name] = Math.random() > 0.5;
            break;
          case 'date':
            const date = new Date();
            date.setDate(date.getDate() - Math.floor(Math.random() * 30));
            row[field.name] = date.toISOString().split('T')[0];
            break;
          case 'datetime':
            const datetime = new Date();
            datetime.setDate(datetime.getDate() - Math.floor(Math.random() * 30));
            row[field.name] = datetime.toLocaleString('zh-CN');
            break;
          default:
            row[field.name] = `${field.name}_${i + 1}`;
        }
      });
      data.push(row);
    }
    
    return { data, total: totalData };
  };

  // 处理特征集预览
  const handlePreviewDataset = (dataset: Dataset) => {
    setPreviewDataset(dataset);
    
    const columns = dataset.columns.map((field: Column) => ({
      title: field.name,
      dataIndex: field.name,
      key: field.name,
      ellipsis: true,
      width: 150
    }));
    setPreviewColumns(columns);
    
    const { data, total } = generatePreviewData(dataset, 1, 10);
    setPreviewData(data);
    setPreviewPagination(prev => ({ ...prev, current: 1, pageSize: 10, total }));
  };

  // 处理预览数据分页
  const handlePreviewPageChange = (page: number, pageSize: number) => {
    if (previewDataset) {
      const { data, total } = generatePreviewData(previewDataset, page, pageSize);
      setPreviewData(data);
      setPreviewPagination(prev => ({ ...prev, current: page, pageSize, total }));
    }
  };

  // 处理特征集下载
  const handleDownloadDataset = (dataset: Dataset) => {
    // 模拟下载功能
    const blob = new Blob([`特征集: ${dataset.name}\n描述: ${dataset.description}\n记录数: ${dataset.rows}`], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${dataset.name}.txt`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('下载成功');
  };

  // 处理特征集删除
  const handleDeleteDataset = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个特征集吗？删除后相关数据将无法恢复。',
      onOk: async () => {
        try {
          const response = await mockService.datasets.delete(id);
          if (response.success) {
            message.success('删除成功');
            loadDatasets();
            if (previewDataset?.id === id) {
              setPreviewDataset(null);
            }
          } else {
            message.error(response.error || '删除失败');
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理特征集分析
  const handleAnalyzeDataset = (dataset: Dataset) => {
    setCurrentAnalysisResult(null);
    setAnalyzedDataset(dataset);
    
    // 检查是否有预定义的示例数据
    const predefinedResult = mockAnalysisResults[dataset.id];
    if (predefinedResult) {
      // 如果有预定义数据，直接使用
      const newTask: FeatureAnalysisTask = {
        datasetId: dataset.id,
        status: 'completed',
        progress: 100,
        result: predefinedResult
      };
      
      setAnalysisTasks(prev => [...prev.filter(t => t.datasetId !== dataset.id), newTask]);
      setCurrentAnalysisResult(predefinedResult);
      return;
    }
    
    // 否则使用原有的随机生成逻辑
    const newTask: FeatureAnalysisTask = {
      datasetId: dataset.id,
      status: 'pending',
      progress: 0
    };
    
    setAnalysisTasks(prev => [...prev.filter(t => t.datasetId !== dataset.id), newTask]);
    
    setTimeout(() => {
      setAnalysisTasks(prev => prev.map(task => 
        task.datasetId === dataset.id ? { ...task, status: 'running' } : task
      ));
      
      let progress = 0;
      const interval = setInterval(() => {
        progress += 10;
        setAnalysisTasks(prev => prev.map(task => 
          task.datasetId === dataset.id ? { ...task, progress } : task
        ));
        
        if (progress >= 100) {
          clearInterval(interval);
          
          const mockResult: FeatureAnalysisResult = {
            featureCount: dataset.columns.length,
            featureTypes: dataset.columns.reduce((acc, col) => {
              acc[col.type] = (acc[col.type] || 0) + 1;
              return acc;
            }, {} as { [key: string]: number }),
            missingValues: dataset.columns.reduce((acc, col) => {
              acc[col.name] = Math.floor(Math.random() * 5);
              return acc;
            }, {} as { [key: string]: number }),
            dataQuality: {
              completeness: 95 + Math.random() * 5,
              uniqueness: 98 + Math.random() * 2,
              consistency: 92 + Math.random() * 8,
              overallQuality: 94 + Math.random() * 6
            },
            featureStatistics: dataset.columns.filter(col => col.type === 'number').reduce((acc, col) => {
              acc[col.name] = {
                min: Math.floor(Math.random() * 100),
                max: Math.floor(Math.random() * 1000) + 100,
                mean: Math.floor(Math.random() * 500) + 50,
                std: Math.floor(Math.random() * 100) + 10
              };
              return acc;
            }, {} as { [key: string]: { min?: number; max?: number; mean?: number; std?: number } })
          };
          
          setAnalysisTasks(prev => prev.map(task => 
            task.datasetId === dataset.id 
              ? { ...task, status: 'completed', progress: 100, result: mockResult }
              : task
          ));
          
          setCurrentAnalysisResult(mockResult);
        }
      }, 500);
    }, 100);
  };

  // 获取分析任务状态显示
  const getTaskStatusDisplay = (task?: FeatureAnalysisTask) => {
    if (!task) return null;
    
    switch (task.status) {
      case 'pending':
        return <Tag color="default">等待中</Tag>;
      case 'running':
        return (
          <div>
            <Tag color="processing">分析中</Tag>
            <Progress 
              percent={task.progress} 
              status="active" 
              strokeColor={{ from: '#108ee9', to: '#87d068' }}
              style={{ marginTop: 8 }}
              size="small"
            />
          </div>
        );
      case 'completed':
        return <Tag color="success">已完成</Tag>;
      case 'failed':
        return <Tag color="error">分析失败</Tag>;
      default:
        return null;
    }
  };

  // 特征视图表格列定义（暂时未使用，保留用于未来功能）
  // const columns = [ ... ];

  // 特征工程页签内容
  const renderFeatureEngineeringTab = () => {
    if (currentTask) {
      // 显示画布编辑界面
      return (
        <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 200px)' }}>
          {/* 顶部工具栏 */}
          <Card size="small" style={{ marginBottom: '16px' }}>
            <Space>
              <Button onClick={() => setCurrentTask(null)}>返回列表</Button>
              <Text strong>{currentTask.name}</Text>
              <Tag color={currentTask.status === 'completed' ? 'green' : currentTask.status === 'running' ? 'blue' : 'default'}>
                {currentTask.status === 'completed' ? '已完成' : currentTask.status === 'running' ? '运行中' : '待执行'}
              </Tag>
              {currentTask.status === 'running' && (
                <Progress percent={currentTask.progress} size="small" style={{ width: '200px' }} />
              )}
            </Space>
          </Card>
          
          {/* 主要内容区域 */}
          <div style={{ display: 'flex', flex: 1, gap: '16px', overflow: 'hidden' }}>
            {/* 左侧画布 */}
            <Card style={{ flex: 2, overflow: 'auto' }}>
              <FeatureFlowCanvas
                flowData={flowData}
                onFlowChange={handleFlowChange}
                logs={logs}
              />
            </Card>
            
            {/* 右侧YAML显示 */}
            <Card 
              title="YAML配置" 
              style={{ width: '400px', overflow: 'auto' }}
              extra={<Button size="small" icon={<FileTextOutlined />} onClick={() => {
                const blob = new Blob([yamlContent], { type: 'text/yaml' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `${currentTask.name}.yaml`;
                a.click();
                URL.revokeObjectURL(url);
              }}>下载</Button>}
            >
              <TextArea
                value={yamlContent}
                readOnly
                style={{ 
                  fontFamily: 'monospace', 
                  fontSize: '12px',
                  height: '100%',
                  minHeight: '500px'
                }}
              />
            </Card>
          </div>
          
          {/* 底部日志窗口 */}
          <Card 
            title="执行日志" 
            size="small" 
            style={{ marginTop: '16px', maxHeight: '200px' }}
            extra={
              <Space>
                <Button 
                  type="primary" 
                  icon={<PlayCircleOutlined />} 
                  onClick={handleRunTask}
                  loading={isRunning}
                  disabled={isRunning || currentTask.status === 'running'}
                >
                  运行
                </Button>
                <Button onClick={() => setLogs([])}>清空</Button>
              </Space>
            }
          >
            <div style={{ 
              background: '#001529', 
              color: '#fff', 
              padding: '12px', 
              borderRadius: '4px',
              fontFamily: 'monospace',
              fontSize: '12px',
              maxHeight: '150px',
              overflowY: 'auto'
            }}>
              {logs.length === 0 ? (
                <Text type="secondary" style={{ color: '#888' }}>暂无日志</Text>
              ) : (
                logs.map((log, index) => (
                  <div key={index} style={{ marginBottom: '4px' }}>{log}</div>
                ))
              )}
            </div>
          </Card>
        </div>
      );
    }
    
    // 显示任务列表
    return (
      <Card>
        <div className="section-header">
          <Title level={4}>特征工程任务</Title>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateTask}>
            创建任务
          </Button>
        </div>
        
        <Text type="secondary">
          通过可视化工作流编辑器创建特征工程任务，支持拖拽组件、连接节点、配置属性
        </Text>
        
        <Divider />
        
        <Table
          dataSource={featureTasks}
          columns={[
            {
              title: '任务名称',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '特征集',
              key: 'dataset',
              render: (_, record) => {
                const dataset = datasets.find(d => d.id === record.datasetId);
                return dataset?.name || record.datasetId;
              }
            },
            {
              title: '状态',
              dataIndex: 'status',
              key: 'status',
              render: (status: string) => {
                const statusMap: Record<string, { color: string; text: string }> = {
                  pending: { color: 'default', text: '待执行' },
                  running: { color: 'processing', text: '运行中' },
                  completed: { color: 'success', text: '已完成' },
                  failed: { color: 'error', text: '失败' },
                };
                const statusInfo = statusMap[status] || statusMap.pending;
                return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
              },
            },
            {
              title: '进度',
              dataIndex: 'progress',
              key: 'progress',
              render: (progress: number) => <Progress percent={progress} size="small" style={{ width: '100px' }} />,
            },
            {
              title: '创建时间',
              dataIndex: 'createdAt',
              key: 'createdAt',
              render: (date: string) => formatDateTime(date),
            },
            {
              title: '操作',
              key: 'action',
              render: (_: any, record: FeatureTask) => (
                <Space size="middle">
                  <Button type="link" icon={<EyeOutlined />} onClick={() => handleOpenTask(record)}>
                    编辑
                  </Button>
                  {record.status === 'running' ? (
                    <Button 
                      type="link" 
                      icon={<PauseOutlined />} 
                      onClick={() => handlePauseTask(record)}
                    >
                      暂停
                    </Button>
                  ) : (
                    <Button 
                      type="link" 
                      icon={<PlayCircleOutlined />} 
                      onClick={() => handleRunTaskFromList(record)}
                      disabled={record.status === 'completed'}
                    >
                      运行
                    </Button>
                  )}
                  <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDeleteTask(record.id)}>
                    删除
                  </Button>
                </Space>
              ),
            },
          ]}
          rowKey="id"
          loading={taskLoading}
          pagination={{ pageSize: 10 }}
        />
      </Card>
    );
  };

  return (
    <Layout className="features-page">
      <Content>
        <Card>
          <div className="section-header">
            <Title level={4}>特征工厂</Title>
          </div>
          
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            items={[
              {
                key: '1',
                label: <span><ToolOutlined /> 特征工程</span>,
                children: renderFeatureEngineeringTab()
              },
              {
                key: '2',
                label: <span><EyeOutlined /> 特征浏览</span>,
                children: (
                  <Card>
                    <Title level={4}>特征浏览</Title>
                    <Text type="secondary">查看当前特征集</Text>
                    
                    <Divider />
                    
                    <Table 
                      dataSource={datasets} 
                      columns={[
                        {
                          title: '特征集名称',
                          dataIndex: 'name',
                          key: 'name',
                        },
                        {
                          title: '上传时间',
                          dataIndex: 'uploadedAt',
                          key: 'uploadedAt',
                          render: (date: string) => date ? new Date(date).toLocaleString('zh-CN') : '-',
                        },
                        {
                          title: '文件大小',
                          dataIndex: 'fileSize',
                          key: 'fileSize',
                          render: (size: number) => formatFileSize(size),
                        },
                        {
                          title: '记录数',
                          dataIndex: 'rows',
                          key: 'rows',
                        },
                        {
                          title: '操作',
                          key: 'action',
                          render: (_: any, record: Dataset) => (
                            <Space size="middle">
                              <Button type="link" icon={<EyeOutlined />} onClick={() => handlePreviewDataset(record)}>预览</Button>
                              <Button type="link" icon={<DownloadOutlined />} onClick={() => handleDownloadDataset(record)}>下载</Button>
                              <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDeleteDataset(record.id)}>删除</Button>
                            </Space>
                          ),
                        },
                      ]} 
                      rowKey="id" 
                      pagination={{ pageSize: 10 }}
                    />
                    
                    {/* 特征集预览表格 */}
                    {previewDataset && (
                      <div style={{ marginTop: '24px' }}>
                        <Card title={`${previewDataset.name} - 数据预览`}>
                          <Table
                            dataSource={previewData}
                            columns={previewColumns}
                            rowKey={(_, index) => String(index)}
                            pagination={{
                              current: previewPagination.current,
                              pageSize: previewPagination.pageSize,
                              total: previewPagination.total,
                              onChange: handlePreviewPageChange,
                              showSizeChanger: true,
                              showQuickJumper: true,
                              showTotal: (total) => `共 ${total} 条记录`
                            }}
                            size="small"
                            scroll={{ x: 'max-content' }}
                          />
                        </Card>
                      </div>
                    )}
                  </Card>
                )
              },
              {
                key: '3',
                label: <span><LineChartOutlined /> 特征分析</span>,
                children: (
                  <Card>
                    <Title level={4}>特征分析</Title>
                    <Text type="secondary">对特征集进行质量分析和统计</Text>
                    
                    <Divider />
                    
                    <Title level={5}>特征集列表</Title>
                    <Table 
                      dataSource={datasets} 
                      columns={[
                        {
                          title: '特征集名称',
                          dataIndex: 'name',
                          key: 'name',
                        },
                        {
                          title: '上传时间',
                          dataIndex: 'uploadedAt',
                          key: 'uploadedAt',
                          render: (date: string) => date ? new Date(date).toLocaleString('zh-CN') : '-',
                        },
                        {
                          title: '记录数',
                          dataIndex: 'rows',
                          key: 'rows',
                        },
                        {
                          title: '分析状态',
                          key: 'analysisStatus',
                          render: (_: any, record: Dataset) => {
                            const task = analysisTasks.find(t => t.datasetId === record.id);
                            return getTaskStatusDisplay(task);
                          },
                        },
                        {
                          title: '操作',
                          key: 'action',
                          render: (_: any, record: Dataset) => {
                            const task = analysisTasks.find(t => t.datasetId === record.id);
                            const isAnalyzing = task?.status === 'running' || task?.status === 'pending';
                            
                            return (
                              <Space size="middle">
                                <Button 
                                  type="primary" 
                                  icon={<LineChartOutlined />} 
                                  onClick={() => handleAnalyzeDataset(record)}
                                  disabled={isAnalyzing}
                                >
                                  分析
                                </Button>
                              </Space>
                            );
                          },
                        },
                      ]} 
                      rowKey="id" 
                      pagination={{ pageSize: 10 }}
                    />
                    
                    {/* 特征分析结果 */}
                    {currentAnalysisResult && analyzedDataset && (
                      <Card title={`${analyzedDataset.name} - 特征分析结果`} style={{ marginTop: 24 }}>
                        <Title level={5}>总体质量评分</Title>
                        <div style={{ display: 'flex', gap: '16px', marginBottom: '24px' }}>
                          <Card size="small" style={{ flex: 1 }}>
                            <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>完整性</p>
                            <p style={{ margin: '8px 0 0 0', fontSize: '24px', fontWeight: 'bold', color: currentAnalysisResult.dataQuality.completeness > 95 ? '#52c41a' : '#faad14' }}>
                              {currentAnalysisResult.dataQuality.completeness.toFixed(1)}%
                            </p>
                          </Card>
                          <Card size="small" style={{ flex: 1 }}>
                            <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>唯一性</p>
                            <p style={{ margin: '8px 0 0 0', fontSize: '24px', fontWeight: 'bold', color: currentAnalysisResult.dataQuality.uniqueness > 95 ? '#52c41a' : '#faad14' }}>
                              {currentAnalysisResult.dataQuality.uniqueness.toFixed(1)}%
                            </p>
                          </Card>
                          <Card size="small" style={{ flex: 1 }}>
                            <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>一致性</p>
                            <p style={{ margin: '8px 0 0 0', fontSize: '24px', fontWeight: 'bold', color: currentAnalysisResult.dataQuality.consistency > 90 ? '#52c41a' : '#faad14' }}>
                              {currentAnalysisResult.dataQuality.consistency.toFixed(1)}%
                            </p>
                          </Card>
                          <Card size="small" style={{ flex: 1 }}>
                            <p style={{ margin: 0, fontSize: '14px', color: '#666' }}>总体质量</p>
                            <p style={{ margin: '8px 0 0 0', fontSize: '24px', fontWeight: 'bold', color: currentAnalysisResult.dataQuality.overallQuality > 95 ? '#52c41a' : '#faad14' }}>
                              {currentAnalysisResult.dataQuality.overallQuality.toFixed(1)}%
                            </p>
                          </Card>
                        </div>
                        
                        <Divider />
                        
                        <Title level={5}>特征统计</Title>
                        <div style={{ marginBottom: '24px' }}>
                          <p><strong>特征总数：</strong>{currentAnalysisResult.featureCount}</p>
                          <p style={{ marginTop: '16px' }}><strong>特征类型分布：</strong></p>
                          <ul>
                            {Object.entries(currentAnalysisResult.featureTypes).map(([type, count]) => (
                              <li key={type}>
                                {type}: {count} 个
                              </li>
                            ))}
                          </ul>
                        </div>
                        
                        <Divider />
                        
                        <Title level={5}>数据问题检测</Title>
                        <div style={{ marginBottom: '24px' }}>
                          <p><strong>缺失值统计：</strong></p>
                          <ul>
                            {Object.entries(currentAnalysisResult.missingValues).map(([col, count]) => (
                              <li key={col}>
                                {col}: {count} 个缺失值 {count > 0 && <Tag color="warning">需要处理</Tag>}
                              </li>
                            ))}
                          </ul>
                        </div>
                        
                        {Object.keys(currentAnalysisResult.featureStatistics).length > 0 && (
                          <>
                            <Divider />
                            <Title level={5}>数值特征统计</Title>
                            <Table
                              dataSource={Object.entries(currentAnalysisResult.featureStatistics).map(([name, stats]) => ({ 
                                name, 
                                min: stats.min, 
                                max: stats.max, 
                                mean: stats.mean?.toFixed(2), 
                                std: stats.std?.toFixed(2) 
                              }))}
                              columns={[
                                { title: '特征名', dataIndex: 'name', key: 'name' },
                                { title: '最小值', dataIndex: 'min', key: 'min' },
                                { title: '最大值', dataIndex: 'max', key: 'max' },
                                { title: '平均值', dataIndex: 'mean', key: 'mean' },
                                { title: '标准差', dataIndex: 'std', key: 'std' }
                              ]}
                              pagination={false}
                              size="small"
                            />
                          </>
                        )}
                      </Card>
                    )}
                  </Card>
                )
              }
            ]}
          />
        </Card>

        {/* 创建任务模态框 */}
        <Modal
          title="创建特征工程任务"
          open={createTaskModalVisible}
          onCancel={() => {
            setCreateTaskModalVisible(false);
            taskForm.resetFields();
          }}
          footer={null}
          width={600}
        >
          <Form
            form={taskForm}
            layout="vertical"
            onFinish={handleTaskSubmit}
          >
            <Form.Item
              name="name"
              label="任务名称"
              rules={[{ required: true, message: '请输入任务名称' }]}
            >
              <Input placeholder="请输入任务名称" />
            </Form.Item>

            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={taskLoading}>
                  创建
                </Button>
                <Button onClick={() => {
                  setCreateTaskModalVisible(false);
                  taskForm.resetFields();
                }}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 创建特征视图模态框（暂时未使用，保留用于未来功能） */}
      </Content>
    </Layout>
  );
};

export default FeaturesPage;

